﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Vra.Entities;

namespace Vra.DataAccess
{
	/// <summary>
	/// Класс реализует доступ к данным <seealso cref="Artist"/>
	/// </summary>
	internal class ArtistDao : BaseEntityDao<Artist>, IArtistDao
	{
		public override IList<Artist> Load()
		{
			IList<Artist> items = new List<Artist>();
			using(var conn = GetConnection())
			{
				conn.Open();
				using(SqlCommand cmd = new SqlCommand(GetSelectQuery(), conn))
				{
					var reader = cmd.ExecuteReader();
					while (reader.Read())
					{
						//Сюда бы Reflection прикрутить.
						Artist artist = new Artist();
						if (ColumnExists(reader, "ArtistId"))
							artist.ArtistId = reader.GetInt32(reader.GetOrdinal("ArtistId"));
						if (ColumnExists(reader,"BirthYear"))
							artist.BirthYear = Convert.ToInt16(reader.GetDecimal(reader.GetOrdinal("BirthYear")));
						if (ColumnExists(reader,"DeceaseYear"))
							artist.DeceaseYear = Convert.ToInt16(reader.GetDecimal(reader.GetOrdinal("DeceaseYear")));
						if (ColumnExists(reader,"Name"))
							artist.Name = reader.GetString(reader.GetOrdinal("Name"));
						if (ColumnExists(reader,"Nationality"))
							artist.Nationality = reader.GetString(reader.GetOrdinal("Nationality"));
						items.Add(artist);
					}
				}
			}
			return items;
		}

		public override void Add(Artist item)
		{
			string query = string.Format("insert into {0} (Name, BirthYear, DeceaseYear, Nationality) values (@Name, @BirthYear, @DeceaseYear, @Nationality)", TableName);
			using (var conn = GetConnection())
			{
				using (var cmd = new SqlCommand(query, conn))
				{
					cmd.Parameters.AddWithValue("@Name", item.Name);
					cmd.Parameters.AddWithValue("@BirthYear", item.BirthYear);
					cmd.Parameters.AddWithValue("@DeceaseYear", item.DeceaseYear);
					cmd.Parameters.AddWithValue("@Nationality", item.Nationality);
					cmd.ExecuteNonQuery();
				}
			}
		}

		public override void Update(Artist item)
		{
			throw new NotImplementedException();
		}

		public override void Delete(int id)
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// Возвращает значение колонки по ее названию
		/// </summary>
		/// <typeparam name="T">возвращаемый тип значения</typeparam>
		/// <param name="reader">Объект типа <seealso cref="IDataReader"/></param>
		/// <param name="columnName">Название колонки</param>
		/// <returns>Значение колонки</returns>
		private static object Get(IDataReader reader, string columnName)
		{
			if (reader == null || string.IsNullOrEmpty(columnName))
				return null;
			try
			{
				reader.GetOrdinal(columnName);
			}
			catch(IndexOutOfRangeException)
			{
				return null;
			}
			object value = reader[columnName];
			if (value == DBNull.Value)
				return null;
			return value;
		}

		private static bool ColumnExists(IDataReader reader, string columnName)
		{
			if (reader == null || string.IsNullOrEmpty(columnName))
				return false;
			try
			{
				reader.GetOrdinal(columnName);
			}
			catch (IndexOutOfRangeException)
			{
				return false;
			}
			object value = reader[columnName];
			if (value == DBNull.Value)
				return false;
			return true;
		}
	}
}
